﻿/* Copyright (c) 2011-2012, Zetatron Consulting
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Zetatron Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AionCxxLibrary.Models;
using AionCxxLibrary.DAO;
using WorldServer.Models;
using WorldServer.Packets.Server;
using WorldServer.DAO;
using AionCxxLibrary.Utilities;
using AionCxxLibrary.Enums;
using System.Timers;

namespace WorldServer.Services
{
    public class CharacterService
    {
        public static bool CreateCharacter(TCharacter character)
        {
            return CharacterDAO.InsertCharacter(character);
        }

        public static TCharacter LoadCharacterTemplate(int charId)
        {
            TCharacter character = CharacterDAO.SelectCharacterTemplate(charId);
            character.Appearance = CharacterDAO.SelectAppearanceByCharacterId(charId);
            character.Position = CharacterDAO.SelectPositionByCharacterID(charId);
            character.Equipment = ItemDAO.SelectEquipmentsTemplatesByCharacterId(charId);
            return character;
        }

        public static List<TCharacter> LoadCharactersForAccount(int accountId)
        {
            List<int> charsids = CharacterDAO.SelectCharacterIDsByAccount(accountId);
            List<TCharacter> result = new List<TCharacter>();
            foreach(int charid in charsids)
            {
                result.Add(LoadCharacterTemplate(charid));
            }
            return result;
        }

        public static void OnCharacterSelect(ref WorldConnection wc, TCharacter character)
        {
            Log.Debug("Character '" + character.Name + "' joined from the Lobby.");

            // 1. Create the player object
            Character c = new Character(character);
            c.Connection = wc;
            wc.Character = c;

            // 2. Register with LevelService (global warehouse)
            LevelService.AddObject(c);

            // 2a. Recover ChannelID from database
            c.SetChannelID(CharacterDAO.SelectChannelID(c.Template.ID));

            // 2b. Register with underlying instance
            c.LevelInstance = LevelService.GetLevelInstance(c.Position.WorldID, c.GetChannelID(), true);
            c.LevelInstance.Register(c);

            // - Initialize Social stuff.
            SocialService.OnCharacterLogin(ref c);

            // 3. Load and send Skill List
            c.SkillList = new CharacterSkillList(SkillsDAO.SelectSkillsByCharacterID(character.ID), c);
            // 3.1 Calculate new skills
            SkillService.CheckSkillList(c);
            c.SendPacket(new SPkt_SkillList());

            // 4. Send Quests
            QuestService.OnCharacterLogin(ref c);

            // 5. Send Recipe List
            c.Recipes = new RecipeList(c);
            c.SendPacket(new SPkt_RecipeList(c));

            // 6. Send EnterWorldAccepted
            c.SendPacket(new SPkt_EnterWorldAccepted());

            // 7. Send UI Settings (if any)
            byte[] settings = CharacterDAO.SelectSettings(c.Template.ID);
            byte[] quickbars = CharacterDAO.SelectQuickBars(c.Template.ID);
            if (settings != null)
                c.SendPacket(new SPkt_ClientSettings(0, settings));
            if (quickbars != null)
                c.SendPacket(new SPkt_ClientSettings(1, quickbars));

            // 8. Send Inventory
            StorageService.InitializeStorages(ref c);
            // 8.1 Send Equipment
            byte cubeLevel = (byte)((c.Inventory.Size - 27) / 9);
            c.SendPacket(new SPkt_InventoryContents(c.Inventory.FindAll(item => item.Equipped), cubeLevel));
            // 8.2 Send Cube Contents by packs of 10
            List<Item> InventoryNotEquipped = c.Inventory.FindAll(item => !item.Equipped);
            if (InventoryNotEquipped.Count > 0)
            {
                for (int i = 0; i < InventoryNotEquipped.Count; i += 10)
                {
                    c.SendPacket(new SPkt_InventoryContents(InventoryNotEquipped.Skip(i).Take(10), cubeLevel));
                }
            }
            // 8.3 Send Inventory End Packet
            c.SendPacket(new SPkt_InventoryContents());

            // 9. Send Stats
            c.StatsList.ApplyEquipmentBonus(c.Inventory.FindAll(item => item.Equipped && item.Slot != (int)EquipmentSlot.OffMain && item.Slot != (int)EquipmentSlot.OffSub));
            c.SendPacket(new SPkt_CharacterStats());
             
            // 9. Send advanced stigma slot count
            c.SendPacket(new SPkt_InventorySizeUpdate(0, 6));

            // 10. Send Bind Point location
            c.SendPacket(new SPkt_ReturnLocation());

            // 11. Send Atreia Clock
            c.SendPacket(new SPkt_AtreiaClock());

            // 10. Send Player Location
            c.SendPacket(new SPkt_CharacterLocation());

            ThreadPoolManager.Schedule(10000, new Action(delegate()
                {
                    byte[] key = new byte[48];
                    lock (ChatServerKeysRnd)
                    {
                        ChatServerKeysRnd.NextBytes(key);
                    }
                    c.SendPacket(new SPkt_ChatServerKey(key));
                }));
        }

        static Random ChatServerKeysRnd = new Random();
        
        public static void OnDisconnect(Character character)
        {
            if (character == null)
                return;

            Log.Debug("Character '" + character.Template.Name + "' disconnected.");
            
            character.Connected = false;

            LevelService.RemoveObject(character);
            character.LevelInstance.Unregister(character.GetGUID());

            // Broadcast disappearance
            character.NearbyObjects.BroadcastPacket(new SPkt_DespawnObject(character.GetGUID(), 0), false);
            foreach (AionObject obj in character.NearbyObjects)
            {
                if (obj is Character)
                    (obj as Character).LevelInstance.RecalculateNearbyObjects(obj as Character);
            }
            character.NearbyObjects.Clear();
        }

        /// <summary>
        /// Called when a character enters a level (ready on client side).
        /// </summary>
        /// <param name="character"></param>
        public static void OnEnterLevel(Character character)
        {
            Log.Debug("Character '" + character.Template.Name + "' is in World.");
            character.SendPacket(new SPkt_CharacterDetails(character));
        }

    }
}
